import {
	getTodayDateString
} from '../utils/common.js'
const db = uniCloud.database();
export function getUserScore() {
	try {
		const startScore = 1000;
		const value = uni.getStorageSync('myScore');
		if (value && value >= 0) {
			return value;
		} else {
			uni.setStorageSync('myScore', '' + startScore);
			return startScore;
		}
	} catch (e) {
		// error
		return startScore;
	}
}

// 本地数据
export function addUserScore(score) {
	try {
		let value = uni.getStorageSync('myScore');
		let sum = Number(value) + score;
		if (sum < 0) {
			// uni.setStorageSync('myScore', 0);
			uni.showToast({
				title: '积分不够了',
				icon: "none",
				duration: 1500
			})
			return -1;
		} else {
			uni.setStorageSync('myScore', '' + sum);
			return sum;
		}
	} catch (e) {
		// error
		uni.showToast({
			title: '数据异常，请稍后再试',
			icon: "none",
			duration: 1500
		})
		return -1;
	}
}

export function saveUserCloudScoreToLocal(score) {
	uni.setStorageSync("CloudScore", score);
	return getTotalUserScore();
}

// 保存用户增加分数
// type  1是签到 其他是itemtype
// 2 幸运777 3 喜相逢 4好运来
export function saveUserAddScoreToLocal(score, type) {
	const total = getTotalUserScore();
	const sum = total + score;
	if (sum < 0) {
		uni.showToast({
			title: '金币不够了,可以点击金币按钮获取更多金币！',
			icon: "none",
			duration: 1500
		})
	} else {
		const current = uni.getStorageSync('AddScore');
		if (current) {
			const addScore = score + current;
			uni.setStorageSync("AddScore", addScore);
		} else {
			uni.setStorageSync("AddScore", score);
		}
		
		const userid = uni.getStorageSync("userid")
		if (userid && score > 0 && type > 0) {
			db.collection("guagua-userscore-list").add({
				"userid": userid,
				"addscore":  Number(score),
				"scoretype": Number(type),
				"datetime":Number(getTodayDateString())
			}).then(res=>{
				console.log("res: " + JSON.stringify(res));
			});
		}
	}

	return getTotalUserScore();
}

// 获取用户分数
export function getTotalUserScore() {
	const current = uni.getStorageSync('AddScore');
	const currentCloud = uni.getStorageSync('CloudScore');
	const currentScore = Number(current);
	const currentCloudScore = Number(currentCloud);
	if (currentScore && currentCloudScore) {
		return currentScore + currentCloudScore;
	} else {
		if (currentScore) {
			return currentScore;
		} else if (currentCloudScore) {
			return currentCloudScore;
		}
		return 0;
	}
}

// 保存用户分数到云平台
export async function saveUserTotalScoreToCloud() {
	const db = uniCloud.database();
	// 获取当前增加的分数
	const currentScore = uni.getStorageSync('AddScore');
	const openid = uni.getStorageSync("UserOpenId");
	const query = db.collection("open_user").where({
		username: openid
	});
	if (currentScore == 0) {
		return;
	}
	try {
		const res = await query.field('score as score,todayscore,todayscoredate').get();
		if (res.result.data && res.result.data.length) {
			const total = res.result.data[0].score + currentScore;
			let todayscore = res.result.data[0].todayscore;
			let todayscoredate = res.result.data[0].todayscoredate;
			if (res.result.data[0].todayscoredate === getTodayDateString()) {
				todayscore = todayscore + currentScore;
			} else {
				todayscoredate = getTodayDateString();
				todayscore = currentScore;
			}
			await query.update({
				score: total,
				todayscore,
				todayscoredate
			})
			uni.setStorageSync("AddScore", 0);
			saveUserCloudScoreToLocal(total);
		}
	} catch (e) {
		console.log("保存用户分数到Cloudy异常", e);
	}

}

// 获取用户云储存分数
export async function getUserScoreFromCloud() {
	try {
		const openid = uni.getStorageSync("UserOpenId");
		const userInfo = await db.collection("open_user").where({
			username: openid
		}).field('_id,score as score,avatar,nickname,updateuserdate,register_date').get();
		if (userInfo && userInfo.result.data) {
			uni.setStorageSync("userid",userInfo.result.data[0]._id)
			uni.setStorageSync("registerdate",userInfo.result.data[0].register_date)
			return userInfo.result.data[0];
		}
	} catch (e) {
		console.log("getUserScoreCloud error:" + e);
		return -1;
	}
}

// 签到分数
export function SignInGetScore() {
	let today = getTodayDateString()
	try {
		uni.showToast({
			title: '获取500金币成功',
			icon: "success",
			duration: 1500
		})
		uni.setStorageSync('SignIn', today)
		const value = uni.getStorageSync('AddScore');
		if (value) {
			uni.setStorageSync('AddScore', Number(value) + 500)
		} else {
			uni.setStorageSync('AddScore', 500);
		}
		return getTotalUserScore();
	} catch (e) {
		// error
		return getTotalUserScore();
	}
}


// 签到分数
export function SignInGetScoreLocal() {

	let today = getTodayDateString()
	try {
		const value = uni.getStorageSync('SignIn');
		if (value === today) {
			uni.showToast({
				title: '已签到，明天再来试试吧',
				icon: "none",
				duration: 1500
			})
			return getUserScore();
		} else {
			uni.showToast({
				title: '签到成功',
				icon: "success",
				duration: 1500
			})
			uni.setStorageSync('SignIn', today)
			const value = uni.getStorageSync('myScore');
			if (value && value > 0) {
				uni.setStorageSync('myScore', Number(value) + 200)
			} else {
				uni.setStorageSync('myScore', 200);
			}
		}
		return getUserScore();
	} catch (e) {
		// error
		return getUserScore();
	}
}